<template>
    <div>
        <div class="layout-route" v-show="!editData.visible">
            <div class="card card-search">
                <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                    <el-form-item label="商品sku" prop="seller_sku">
                        <el-input v-model.trim="queryParams.seller_sku" placeholder="请输入商品sku" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="SPU" prop="spu">
                        <el-input v-model.trim="queryParams.spu" placeholder="请输入SPU" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="采购者" prop="operate_id">
                        <el-select v-model="queryParams.operate_id" placeholder="请选择采购者" clearable size="small" style="width: 240px">
                            <el-option v-for="(dict, index) in dict.salesmanList" :key="index" :label="dict.username" :value="dict.operater_id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="供应商" prop="supply_id">
                        <SelectPage
                            v-model="queryParams.supply_id"
                            placeholder="请选择供应商"
                            :url="$api.supply.getSupplyList"
                            show_field="supply_name"
                            query_field="supply_name"
                            query_field2="spu"
                            filterable
                            clearable
                            popper-class="custom-select"
                            style="width: 240px"
                        ></SelectPage>
                    </el-form-item>
                    <el-form-item label="创建时间" prop="create_time">
                        <el-date-picker v-model="queryParams.create_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <div class="card">
                <!-- <el-row :gutter="10" class="mb8">
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row> -->
                <el-tabs v-model="queryParams.purchase_status" type="border-card" @tab-click="handleQuery">
                    <el-tab-pane label="全部" :name="undefined"></el-tab-pane>
                    <el-tab-pane :label="`正常采购(${total_normal})`" name="1"></el-tab-pane>
                    <el-tab-pane :label="`暂不采购(${total_not})`" name="2"></el-tab-pane>
                </el-tabs>
                <div class="table-wrap">
                    <el-table v-loading="loading" :data="tableData" row-key="id" border script :span-method="arraySpanMethod" default-expand-all class="expend-table">
                        <!-- <el-table-column type="selection" width="50"></el-table-column> -->
                        <el-table-column label="" type="expand" width="50">
                            <template slot-scope="scope">
                                <!-- :span-method="objectSpanMethod"  -->
                                <el-table :data="scope.row.sku_info" border :show-header="false" class="sub-table">
                                    <el-table-column type="selection" width="50"> </el-table-column>
                                    <el-table-column label="" prop="order_id" min-width="250">
                                        <template #header>
                                            <div class="flex column align-center">
                                                <span>商品信息</span>
                                                <span>[上次采购价/平均采购价]</span>
                                            </div>
                                        </template>
                                        <template slot-scope="subScope">
                                            <div class="flex">
                                                <div style="width: 60px">
                                                    <ImageUploadImg v-model="subScope.row.image_url" :readOnly="true" class="small-img"></ImageUploadImg>
                                                </div>
                                                <div>
                                                    <el-link type="primary">{{ subScope.row.seller_sku }}</el-link>
                                                    <div>{{ subScope.row.spu }}</div>
                                                    <div>[￥{{ subScope.row.purchase_price }} / ￥{{ subScope.row.review_price }}]</div>
                                                    <div>{{ subScope.row.warehouse }}</div>
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" min-width="100" prop="inventory_quantity" align="center"></el-table-column>
                                    <el-table-column label="在途" min-width="100" prop="on_way_quantity" align="center"></el-table-column>
                                    <el-table-column label="订单" min-width="100" prop="sku_1days" align="center"></el-table-column>
                                    <el-table-column label="安全" min-width="100" prop="safe_quantity" align="center"></el-table-column>
                                    <el-table-column label="备货" min-width="100" prop="suggest_days" align="center"></el-table-column>
                                    <el-table-column label="日均" min-width="100" prop="day_90_one" align="center"></el-table-column>
                                    <el-table-column label="3/7/15/30" min-width="140" prop="_3/7/15/30" align="center">
                                        <template slot-scope="subScope"
                                            >{{ subScope.row.sku_3days }}/{{ subScope.row.sku_7days }}/{{ subScope.row.sku_15days }}/{{ subScope.row.sku_30days }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="计划中" min-width="100" prop="_计划中" align="center">
                                        <template slot-scope="subScope">[{{ subScope.row.pre_suggest_quantity }}] </template>
                                    </el-table-column>
                                    <el-table-column label="建议数量" min-width="140" align="center">
                                        <template slot-scope="subScope">
                                            <div class="flex column align-center">
                                                <el-tooltip placement="top" effect="light">
                                                    <div slot="content">
                                                        <div style="margin-bottom: 4px">建议数量 =（订单量+安全库存） - （在途+库存） - 采购计划中</div>
                                                        <div>
                                                            {{
                                                                `${subScope.row.suggest_quantity} =（${subScope.row.sku_1days}+${subScope.row.safe_quantity}）-（${subScope.row.on_way_quantity}+${subScope.row.inventory_quantity}）-  ${subScope.row.pre_suggest_quantity}`
                                                            }}
                                                        </div>
                                                    </div>
                                                    <div style="color: #f40">{{ subScope.row.suggest_quantity }}</div>
                                                </el-tooltip>

                                                <div ref="editPopover">
                                                    <span slot="reference" @click="showEditPopover(subScope.row, scope.$index)" v-if="!subScope.row.edit">
                                                        [{{ subScope.row.purchase_quantity }}]
                                                        <i class="el-icon-edit-outline" ref="editBtn" style="color: #11a983"></i>
                                                    </span>
                                                    <div class="flex items-center justify-between" v-else>
                                                        <el-input
                                                            v-model="editModal.purchase_quantity"
                                                            :autofocus="true"
                                                            @blur="editBlur(subScope.row, scope.$index)"
                                                            placeholder="请输入采购数量"
                                                            size="mini"
                                                            style="width: 80px"
                                                            v-if="subScope.row.edit"
                                                        ></el-input>
                                                        <el-button size="mini" type="text" style="padding: 7px 4px" @click="updatePurchaseQuantity(subScope.row)">确定</el-button>
                                                        <el-button size="mini" type="text" style="margin-left: 0" @click="hideEditPopover(subScope.row, scope.$index)">取消</el-button>
                                                    </div>
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="采购员" min-width="200" align="center">
                                        <template slot-scope="subScope">
                                            <div>{{ subScope.row.operater || '无' }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="120" fixed="right">
                                        <template slot-scope="subScope">
                                            <div>
                                                <el-button type="text" @click="addToCart(subScope.row, $event)">加入计划</el-button>
                                            </div>
                                            <el-popover placement="top" trigger="hover">
                                                <el-button slot="reference" type="text">更多<i class="el-icon-arrow-down"></i></el-button>
                                                <div>
                                                    <div><el-button type="text" @click="showChangeSupply(subScope.row)">更换供应商</el-button></div>
                                                    <div><el-button type="text" @click="unPurchase(subScope.row)" v-if="subScope.row.purchase_status == 1">暂不采购</el-button></div>
                                                    <div><el-button type="text" @click="addRemark(subScope.row)">备注</el-button></div>
                                                </div>
                                            </el-popover>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>
                        </el-table-column>
                        <el-table-column label="商品信息" prop="order_id" min-width="250">
                            <template #header>
                                <div class="flex column align-center">
                                    <span>商品信息</span>
                                    <span>[上次采购价/平均采购价]</span>
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <div class="flex">
                                    <span style="position: relative; padding-right: 36px">
                                        供应商：{{ scope.row.supply_name }}
                                        <sub style="font-size: 12px; color: #ffba00; position: absolute; right: 8px; top: -4px">1688</sub>
                                    </span>

                                    <el-link type="warning">一键生成采购订单</el-link>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="基础建议量" align="center">
                            <el-table-column label="库存" min-width="100" align="center">
                                <template #header>
                                    <span>库存</span>
                                    <el-tooltip content="库存" placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="在途" min-width="100" align="center"></el-table-column>
                            <el-table-column label="订单" min-width="100" align="center"></el-table-column>
                        </el-table-column>

                        <el-table-column label="智能预测备货量" align="center">
                            <el-table-column label="安全" min-width="100" align="center">
                                <template #header>
                                    <span>安全</span>
                                    <el-tooltip content="安全" placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="备货" min-width="100" align="center"></el-table-column>
                            <el-table-column label="日均" min-width="100" align="center"></el-table-column>
                            <el-table-column label="3/7/15/30" min-width="140" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="计划中" min-width="100" align="center"></el-table-column>
                        <el-table-column label="建议数量" min-width="140" align="center">
                            <template #header>
                                <div class="flex column align-center"><span>建议数量</span><span>[采购数量]</span><i class="el-icon-refresh" style="color: #11a983" @click="resetQuery"></i></div>
                            </template>
                            <template slot-scope="scope">
                                <div style="text-align: left;">SKU种类：{{ scope.row.sku_nums }}，商品总数：{{ scope.row.sku_quantity }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="采购员" min-width="200"></el-table-column>
                        <el-table-column label="操作" width="120" fixed="right"></el-table-column>
                    </el-table>
                </div>
                <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
            </div>

            <ChangeSupplyDialog v-model="changeSupplyDialog.visible" v-if="changeSupplyDialog.visible" :params="changeSupplyDialog.data" @success="handleQuery"></ChangeSupplyDialog>
            <RemarkDialog v-model="remarkDialog.visible" :params="remarkDialog.data" @success="handleQuery"></RemarkDialog>

            <!-- 购物车图标 -->
            <div
                ref="cart"
                @click="cartVisible = !cartVisible"
                style="position: fixed; right: 20px; top: 40%; width: 50px; padding: 12px; background: #fff; z-index: 9999; text-align: center; box-shadow: 0 0 4px #ccc; cursor: pointer;"
                v-show="!cartVisible"
            >
                <span>采购计划</span>
                <el-badge :value="cartCount" class="cart-icon" style="margin-top: 8px">
                    <i class="el-icon-shopping-cart-2" style="font-size: 24px"></i>
                </el-badge>
            </div>
            <CartDrawer v-model="cartVisible" ref="cartDrawer" @getCartCount="getCartCount"></CartDrawer>
        </div>
    </div>
</template>
<script>
import { getSuggestList, unPurchase, updatePurchaseQuantity, addPurchasePlan, getPurchaserList } from '@/api/purchase'
import { parseTime } from '@/utils/quickadmin'
import ChangeSupplyDialog from './components/changeSupplyDialog.vue'
import RemarkDialog from './components/remarkDialog.vue'
import CartDrawer from './components/cartDrawer.vue'
export default {
    name: 'PurchaseSuggest',
    components: { ChangeSupplyDialog, RemarkDialog, CartDrawer },
    data() {
        return {
            cartVisible: false,
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            total_normal: 0,
            total_not: 0,

            // 状态数据字典
            dict: {
                salesmanList: [],
            },
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                purchase_status: undefined,
                seller_sku: undefined,
                spu: undefined,
                operate_id: undefined,
                supply_id: undefined,
                create_time: [],
            },
            syncDialog: {
                visible: false,
                data: {},
            },
            remarkDialog: {
                visible: false,
                data: {},
            },
            changeSupplyDialog: {
                visible: false,
                data: {},
            },
            editModal: {
                id: '',
                purchase_quantity: '',
            },
            editData: {
                visible: false,
                data: {},
            },
            cartPosition: { x: 0, y: 0 },
            cartCount: 0,
        }
    },

    async created() {
        this.loading = true
        try {
            const salesmanData = await getPurchaserList()
            this.dict.salesmanList = salesmanData?.data ?? []
        } catch (error) {
            this.loading = false
        }
        this.getList()
        this.getTotal()
    },
    mounted() {
        this.updateCartPosition()
        window.addEventListener('resize', this.updateCartPosition)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.updateCartPosition)
    },
    methods: {
        addRemark(row) {
            this.remarkDialog.visible = true
            this.remarkDialog.data = row
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1) {
                return [1, 9]
            } else if (columnIndex === 0 || columnIndex == 12) {
                return [1, 1]
            } else if (columnIndex == 10) {
                return [1, 2]
            } else {
                return [0, 0]
            }
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            const skuList = this.tableData.find(item => item.order_id === row.order_id)?.sku_info
            // 判断是否需要合并单元格的列
            if ([1, 2, 3, 4, 5, 6, 7].includes(columnIndex)) {
                if (rowIndex === 0) {
                    return {
                        rowspan: skuList.length,
                        colspan: 1,
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    }
                }
            }
        },
        getTotal() {
            const params_1 = {
                create_time: [],
                limit: 10,
                page: 1,
                purchase_status: 1,
            }
            getSuggestList(params_1)
                .then(response => {
                    this.total_normal = response.data.total
                })
                .catch(() => {})
            const params_2 = {
                create_time: [],
                limit: 10,
                page: 1,
                purchase_status: 2,
            }
            getSuggestList(params_2)
                .then(response => {
                    this.total_not = response.data.total
                })
                .catch(() => {})
        },
        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            getSuggestList(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                    // 根据tableData.sku_info的长度，初始化edit
                    this.tableData.map(temp => {
                        temp.sku_info.forEach(item => {
                            item.edit = false
                            return { ...item }
                        })
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
        showChangeSupply(row) {
            this.changeSupplyDialog.visible = true
            this.changeSupplyDialog.data = row
        },

        // 删除按钮操作
        unPurchase(row) {
            this.$confirm('是否确认暂不采购?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    await unPurchase({ id: row.id })
                    this.getList()
                    this.getTotal()
                    this.msgSuccess('操作成功')
                })
                .catch(() => {})
        },
        // 更新购物车坐标
        updateCartPosition() {
            this.$nextTick(() => {
                const rect = this.$refs.cart.getBoundingClientRect()
                this.cartPosition = {
                    x: rect.left + rect.width / 2,
                    y: rect.top + rect.height / 2,
                }
            })
        },
        showEditPopover(row, $index) {
            const updatedSkuInfo = this.tableData[$index].sku_info.map(item => {
                if (item.id === row.id) {
                    return { ...item, edit: true }
                } else {
                    return { ...item, edit: false }
                }
            })
            // 替换原数组
            this.$set(this.tableData[$index], 'sku_info', updatedSkuInfo)

            this.editModal.id = row.id
            this.editModal.purchase_quantity = row.purchase_quantity
        },
        editBlur(row, $index) {
            setTimeout(() => {
                this.hideEditPopover(row, $index)
            }, 500)
        },
        hideEditPopover(row, $index) {
            const updatedSkuInfo = this.tableData[$index].sku_info.map(item => {
                return { ...item, edit: false }
            })
            // 替换原数组
            this.$set(this.tableData[$index], 'sku_info', updatedSkuInfo)

            this.editModal.id = ''
            this.editModal.purchase_quantity = ''
        },
        
        updatePurchaseQuantity() {
            updatePurchaseQuantity(this.editModal)
                .then(() => {
                    this.msgSuccess('操作成功')
                    this.getList()
                })
                .catch(() => {})
        },
        // 添加购物车
        addToCart(item, e) {
            this.createBall(e.clientX, e.clientY)
            addPurchasePlan({ id: item.id })
                .then(() => {
                    this.msgSuccess('操作成功')
                    this.getList()
                    if(this.$refs.cartDrawer) {
                        this.$refs.cartDrawer.getCarPlan()
                    }
                    // this.getCarPlan()
                })
                .catch(() => {})
        },
        getCartCount(count) {
            this.cartCount = count
        },
        // 创建小球动画
        createBall(startX, startY) {
            const ball = document.createElement('div')
            ball.className = 'ball'

            // 初始位置
            ball.style.left = `${startX}px`
            ball.style.top = `${startY}px`
            ball.style.position = 'fixed' // 确保小球是固定定位
            ball.style.opacity = 1 // 确保初始可见
            ball.style.width = '20px' // 小球的宽度
            ball.style.height = '20px' // 小球的高度
            ball.style.backgroundColor = '#f40' // 小球的颜色
            ball.style.borderRadius = '50%' // 圆形
            ball.style.zIndex = 9999 // 确保在最上层
            ball.style.pointerEvents = 'none' // 防止干扰点击事件

            document.body.appendChild(ball)

            // 计算贝塞尔曲线参数
            const cartCenterX = this.cartPosition.x
            const cartCenterY = this.cartPosition.y

            // 控制点（可以调整控制点的位置来改变曲线弧度）
            const controlX = (startX + cartCenterX) / 2 // 控制点的 X 坐标
            const controlY = startY - 50 // 控制点的 Y 坐标（向上抬高弧度）

            // 贝塞尔曲线公式
            const bezierCurve = (t, p0, p1, p2) => {
                return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2
            }

            // 动画时长
            const duration = 500 // 600ms
            let startTime = null

            const animate = timestamp => {
                if (!startTime) startTime = timestamp
                const progress = (timestamp - startTime) / duration // 计算进度 [0, 1]

                if (progress < 1) {
                    // 当前小球的位置
                    const currentX = bezierCurve(progress, startX, controlX, cartCenterX)
                    const currentY = bezierCurve(progress, startY, controlY, cartCenterY)

                    // 更新小球位置
                    ball.style.transform = `translate(${currentX - startX}px, ${currentY - startY}px)`
                    ball.style.opacity = 1

                    // 继续下一帧
                    requestAnimationFrame(animate)
                } else {
                    // 动画结束，移除小球
                    document.body.removeChild(ball)
                }
            }

            requestAnimationFrame(animate)
        },
    },
}
</script>
<style scoped>
.ball {
    display: block;
    position: fixed;
    width: 20px; /* 小球的宽度 */
    height: 20px; /* 小球的高度 */
    background-color: #f40; /* 小球的颜色 */
    border-radius: 50%; /* 圆形 */
    z-index: 9999; /* 确保在最上层 */
    pointer-events: none; /* 防止干扰点击事件 */
    opacity: 1; /* 确保初始可见 */
    transition: all 0.6s cubic-bezier(0.49, -0.29, 0.75, 0.41); /* 动画效果 */
}
::v-deep .expend-table .el-table__expanded-cell[class*='cell'] {
    padding: 0 !important;
}
.custom-select .el-select-dropdown__item {
    max-width: 450px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.border-cell {
    padding: 0 !important;
}
.border-cell .cell {
    padding: 0 !important;
}
.border-cell-item {
    padding: 10px;
    border-bottom: 1px solid #dfe6ec;
}
.border-cell-item:last-child {
    border-bottom: 0;
}
.el-tabs--border-card {
    box-shadow: none;
    border-bottom: 0;
}

::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.table-wrap {
    padding: 4px 0 0 0;
    border-bottom: 1px solid #dfe4ed;
    border-left: 1px solid #dfe4ed;
    border-right: 1px solid #dfe4ed;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
</style>
<style lang="scss" scoped>
.cart-content {
    display: flex;
    flex-direction: column;
    align-items: stretch;
}
::v-deep .cart-body {
    flex: 1;
    .el-checkbox__label {
        width: 0;
        padding: 0;
        color: transparent;
    }
}
.cart-header {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
}
.cart-title {
    font-size: 14px;
    padding: 8px 12px;
    background-color: #ddd;
}
.cart-row {
    font-size: 14px;
    padding: 8px 12px;
    border-bottom: 1px solid #f5f5f5;
}
.cart-footer {
    padding: 8px 12px;
    border-top: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
}
::v-deep .sub-table {
    border: 0;
    &::after {
        background: transparent;
    }
    /* 隐藏子表格的滚动条 */
    .el-table__body-wrapper {
        overflow-x: hidden !important;
    }
}

::v-deep .small-img {
    .upload-img-wrap {
        width: 54px;
    }
    .upload-img-box {
        width: 50px;
        height: 50px;
    }
    .upload-img {
        width: 48px;
        height: 48px;
    }
}
</style>
